package com.hwqsdk.myapplication.practise;

import com.blankj.utilcode.util.ThreadUtils;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Create by Fanketly on 2021/11/24
 * Gitee:https://gitee.com/fanketly
 */
public class Http {
    private static final class S {
        private static final Http H = new Http();
    }

    public static Http getInstance() {
        return S.H;
    }

    private static final OkHttpClient O = new OkHttpClient();
    public static final Gson G = new Gson();
    public static String userId;
    public static String baseUrl;
    public static final MediaType M = MediaType.parse("application/json");

    public <T> void get2(String url, RequestBody requestBody, Class<T> tClass, int i, Task<T> task) {
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<T>() {
            @Override
            public T doInBackground() throws Throwable {
                return get(url, requestBody, tClass, i);
            }

            @Override
            public void onSuccess(T result) {
                task.onSuccess(result);
            }
        });
    }

    public <T> T get(String url, RequestBody requestBody, Class<T> tClass, int i) throws IOException {
//        url = baseUrl + "?" + url + "&userId=" + userId;
        if (i == 1)
            return G.fromJson(O.newCall(new Request.Builder().url(url).build()).execute().body().string(), tClass);
        else
            return G.fromJson(O.newCall(new Request.Builder().url(url).header("Authorization","eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQwZjhkN2JjLWIzZjMtNGJlNi1hNDA2LTBiODJmMGM5YjY2MiJ9.FqceBzE1FRdickMaEAM0gnnq0Qnf4kn6DfmSfgelxpkwqyf4Go3r7R40BM27cCDrdOZ6ex7SKj_FoIPcL2t22Q").post(requestBody).build()).execute().body().string(), tClass);
    }

    public interface Task<T> {
        void onSuccess(T t);
    }
}
